package com.kang.controller;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.SessionAttributes;

import com.alibaba.fastjson.JSON;
import com.kang.pojo.AjaxResult;
import com.kang.pojo.Audit;
import com.kang.pojo.ItemDetail;
import com.kang.pojo.PurchaseOrder;
import com.kang.pojo.PurchaseOrderItem;
import com.kang.pojo.ReturnRequest;
import com.kang.pojo.ReturnRequestItem;
import com.kang.service.AssistService;
import com.kang.service.AuditService;
import com.kang.service.CategoryService;
import com.kang.service.ReturnRequestService;
import com.kang.service.WarehouseService;
import com.kang.until.OtherRealizePDF;
import com.kang.until.PurchaseOrderPDF;
import com.vonechina.entity.page.ItemDetailPage;
import com.vonechina.entity.page.ReturnRequestPage;

/**
 * 退货申请控制层
 * 
 * @author zs614
 *
 */
@Controller
@RequestMapping("returnRequest")
@SessionAttributes({ "returnRequestPage" })
public class ReturnRequestController extends com.kang.controller.Controller {
	/**
	 * 退货申请服务层
	 */
	@Resource
	private ReturnRequestService requestService;
	/**
	 * 通用服务层
	 */
	@Resource
	private AssistService assistService;
	/**
	 * 仓库服务层
	 */
	@Resource
	private WarehouseService warehouseService;
	/**
	 * 物品分类服务层
	 */
	@Resource
	private CategoryService cService;
	/**
	 * 审核服务层
	 */
	@Resource
	private AuditService auditService;

	/**
	 * 分页查询退货申请
	 * 
	 * @param session
	 * @param model
	 * @param returnRequestPage
	 *            搜索条件自动封装
	 * @return 返回jsp页面
	 */
	@RequestMapping("listReturnRequest")
	public String listReturnRequest(HttpSession session, Model model, ReturnRequestPage returnRequestPage) {		
		initRight(session);
		if (checkRight("查看退货申请") != SUCCESS && checkRight("查看全部退货申请") != SUCCESS) {
			return "basic/noRight";
		}
		if (checkRight("查看全部退货申请") == SUCCESS) {
			returnRequestPage.setCreatePersonID(null);
		} else {
			returnRequestPage.setCreatePersonID(userID);
		}
		model.addAttribute("isAdd", checkRight("新增退货申请") == SUCCESS);
		model.addAttribute("warehouseList", warehouseService.listAllWarehouse());
		model.addAttribute("requestList", requestService.listReturnRequest(returnRequestPage));
		returnRequestPage.setPageUrl("returnRequest/listReturnRequest.do");
		model.addAttribute("page", returnRequestPage);
		return "business/returnRequest/listReturnRequest";
	}

	/**
	 * 前往新增退货申请界面
	 * 
	 * @param session
	 * @param model
	 * @return 返回jsp页面
	 */
	@RequestMapping("toAdd")
	public String toAddReturnRequest(HttpSession session, Model model) {
		initRight(session);
		if (checkRight("新增退货申请") != SUCCESS) {
			return "basic/noRight";
		}
		model.addAttribute("organizations", assistService.listOrganization());
		model.addAttribute("cruiseList", assistService.listCruise());
		model.addAttribute("warehouseList", warehouseService.listAllWarehouse());
		model.addAttribute("categoryList", cService.listAllCategory());
		return "business/returnRequest/addReturnRequest";
	}

	/**
	 * 获取退货申请可用物品
	 * 
	 * @param page
	 *            搜索条件自动封装
	 * @return 返回json字符串
	 */
	@RequestMapping("listNotAddItem")
	@ResponseBody
	public String listNotAddItem(ItemDetailPage page) {

		AjaxResult result = new AjaxResult();
		List<ItemDetail> list = requestService.listItemDetailForReturn(page);
		result.setTotal(page.getRows());
		result.setRows(list);
		return JSON.toJSONString(result);
	}

	/**
	 * 新增退货申请
	 * 
	 * @param session
	 * @param request
	 *            退货实体类申请自动封装
	 * @param itemIds
	 *            退货申请物品来源ID数组
	 * @param number
	 *            退货申请物品退货数量数组
	 * @return 返回json字符串
	 */
	@RequestMapping("add")
	@ResponseBody
	public String addReturnRequest(HttpSession session, ReturnRequest request, Integer[] itemIds, Integer[] number) {
		initRight(session);
		AjaxResult result = new AjaxResult();
		if (checkRight("新增退货申请") != SUCCESS) {
			result.setResult("noRight");
			return JSON.toJSONString(result);
		}
		request.setApplicationNo(requestService.generateReturnRequestCode());
		request.setCreatePersonID(userID);
		request.setLastModifiedID(userID);

		if (request.getStatus() == 1 && !requestService.checkItemNumberEnough(itemIds, number)) {
			result.setError("物资数量不足，请刷新页面后重试！");
			return JSON.toJSONString(result);
		}
		int a = requestService.insertReturnRequest(request);
		if (a > 0) {
			requestService.saveReturnItem(request.getReturnRequestID(), itemIds, number);
			if (request.getStatus() == 1) {
				request.setSubmitterID(userID);
				requestService.submitReturnRequest(request);
				requestService.subtractStock(itemIds, number);
				Audit audit = new Audit();
				audit.setAuditType(3);
				audit.setSourceID(request.getReturnRequestID());
				audit.setLastPersonID(userID);
				audit.setMoney("0");
				auditService.addAudit(audit);
				requestService.updateStatus(request.getReturnRequestID(), 2);
			}
			result.setResult("success");
		}
		return JSON.toJSONString(result);
	}

	/**
	 * 查看退货申请详情
	 * 
	 * @param session
	 * @param model
	 * @param returnRequestID
	 *            退货申请ID
	 * @return 返回jsp页面
	 */
	@RequestMapping("toEdit")
	public String toEditReturnRequest(HttpSession session, Model model, Integer returnRequestID) {
		initRight(session);
		ReturnRequest order = requestService.selectReturnRequestByID(returnRequestID);
		if (order.getCreatePersonID() == userID && checkRight("新增退货申请") == SUCCESS && order.getStatus() == 0) {
			model.addAttribute("isEdit", true);
		} else if (checkRight("编辑全部退货申请") == SUCCESS && order.getStatus() == 0) {
			model.addAttribute("isEdit", true);
		} else {
			model.addAttribute("isEdit", false);
		}
		model.addAttribute("organizations", assistService.listOrganization());
		model.addAttribute("cruiseList", assistService.listCruise());
		model.addAttribute("returnRequest", requestService.selectReturnRequestByID(returnRequestID));
		model.addAttribute("itemList", requestService.listItemByReturnRequestID(returnRequestID));
		model.addAttribute("warehouseList", warehouseService.listAllWarehouse());
		model.addAttribute("categoryList", cService.listAllCategory());
		return "business/returnRequest/editReturnRequest";
	}

	/**
	 * 编辑退货申请
	 * 
	 * @param session
	 * @param request
	 *            退货实体类申请自动封装
	 * @param itemIds
	 *            退货申请物品来源ID数组
	 * @param number
	 *            退货申请物品退货数量数组
	 * @return 返回json字符串
	 */
	@RequestMapping("edit")
	@ResponseBody
	public String editReturnRequest(HttpSession session, ReturnRequest request, Integer[] itemIds, Integer[] number) {
		initRight(session);
		AjaxResult result = new AjaxResult();
		if (requestService.selectReturnRequestByID(request.getReturnRequestID()).getCreatePersonID() == userID
				&& checkRight("新增退货申请") == SUCCESS) {

		} else if (checkRight("编辑全部退货申请") == SUCCESS) {

		} else {
			result.setResult("noRight");
			return JSON.toJSONString(result);
		}
		request.setLastModifiedID(userID);
		int a = requestService.updateReturnRequest(request);
		if (a > 0) {
			requestService.saveReturnItem(request.getReturnRequestID(), itemIds, number);
			result.setResult("success");
		}
		return JSON.toJSONString(result);
	}

	/**
	 * 保存并提交退货申请
	 * 
	 * @param session
	 * @param request
	 *            退货实体类申请自动封装
	 * @param itemIds
	 *            退货申请物品来源ID数组
	 * @param number
	 *            退货申请物品退货数量数组
	 * @return 返回json字符串
	 */
	@RequestMapping("saveAndSubmit")
	@ResponseBody
	public String saveAndSubmit(HttpSession session, ReturnRequest request, Integer[] itemIds, Integer[] number) {
		initRight(session);
		AjaxResult result = new AjaxResult();
		if (requestService.selectReturnRequestByID(request.getReturnRequestID()).getCreatePersonID() == userID
				&& checkRight("新增退货申请") == SUCCESS) {

		} else if (checkRight("编辑全部退货申请") == SUCCESS) {

		} else {
			result.setResult("noRight");
			return JSON.toJSONString(result);
		}
		request.setLastModifiedID(userID);
		if (!requestService.checkItemNumberEnough(itemIds, number)) {
			result.setError("物资数量不足，请刷新页面后重试！");
			return JSON.toJSONString(result);
		}
		int a = requestService.updateReturnRequest(request);
		request.setSubmitterID(userID);
		requestService.submitReturnRequest(request);
		if (a > 0) {
			Audit audit = new Audit();
			audit.setAuditType(3);
			audit.setSourceID(request.getReturnRequestID());
			audit.setLastPersonID(userID);
			audit.setMoney("0");
			auditService.addAudit(audit);
			requestService.updateStatus(request.getReturnRequestID(), 2);
			requestService.saveReturnItem(request.getReturnRequestID(), itemIds, number);
			requestService.subtractStock(itemIds, number);
			result.setResult("success");
		}
		return JSON.toJSONString(result);
	}

	/**
	 * 删除未提交退货申请
	 * 
	 * @param session
	 * @param returnRequestID
	 *            退货申请ID
	 * @return 返回json字符串
	 */
	@RequestMapping("delete")
	@ResponseBody
	public String delete(HttpSession session, Integer returnRequestID) {
		initRight(session);
		AjaxResult result = new AjaxResult();
		if (requestService.selectReturnRequestByID(returnRequestID).getCreatePersonID() == userID
				&& checkRight("新增退货申请") == SUCCESS) {

		} else if (checkRight("编辑全部退货申请") == SUCCESS) {

		} else {
			result.setResult("noRight");
			return JSON.toJSONString(result);
		}
		int a = requestService.deleteByPrimaryKey(returnRequestID);
		if (a > 0) {
			result.setResult("success");
		}
		return JSON.toJSONString(result);
	}

	/**
	 * 提交退货申请
	 * 
	 * @param session
	 * @param returnRequestID
	 *            退货申请ID
	 * @return 返回json字符串
	 */
	@RequestMapping("submit")
	@ResponseBody
	public String submit(HttpSession session, Integer returnRequestID) {
		initRight(session);
		AjaxResult result = new AjaxResult();
		ReturnRequest request = requestService.selectReturnRequestByID(returnRequestID);
		if (request.getCreatePersonID() == userID && checkRight("新增退货申请") == SUCCESS) {

		} else if (checkRight("编辑全部退货申请") == SUCCESS) {

		} else {
			result.setResult("noRight");
			return JSON.toJSONString(result);
		}

		List<ReturnRequestItem> list = requestService.listItemByReturnRequestID(returnRequestID);
		Integer[] itemIds = new Integer[list.size()];
		Integer[] number = new Integer[list.size()];
		for (int i = 0; i < list.size(); i++) {
			itemIds[i] = list.get(i).getSourceID();
			number[i] = list.get(i).getNumber();
		}

		if (!requestService.checkItemNumberEnough(itemIds, number)) {
			result.setError("物资数量不足，请刷新页面后重试！");
			return JSON.toJSONString(result);
		}
		request.setSubmitterID(userID);
		int a = requestService.submitReturnRequest(request);
		if (a > 0) {
			Audit audit = new Audit();
			audit.setAuditType(3);
			audit.setSourceID(request.getReturnRequestID());
			audit.setLastPersonID(userID);
			audit.setMoney("0");
			auditService.addAudit(audit);
			requestService.updateStatus(request.getReturnRequestID(), 2);
			requestService.subtractStock(itemIds, number);
			result.setResult("success");
		}
		return JSON.toJSONString(result);
	}
	
	/**
	 * 导出退货申请PDF文件
	 * 
	 * @param session
	 * @param response
	 * @param returnOrderID
	 *            退货订单ID
	 * @throws Exception
	 */
	@RequestMapping("download")
	public void downloadPDF(HttpSession session, HttpServletResponse response,ReturnRequest request, int returnRequestID)
			throws Exception {
		System.out.println("==============退货订单详情================");
		
		//List<PurchaseOrderItem> list = orderService.listItemForOrder(purchaseOrderID);
		ReturnRequest rrq = requestService.selectReturnRequestByID(returnRequestID);
		List<ReturnRequestItem> list = requestService.listItemByReturnRequestID(returnRequestID);
		//此方法为直接下载文件
		File file = OtherRealizePDF.buildReturnRequestPDF(rrq,list);
		if (file.isFile() && file.exists()) {
			try {
				 InputStream fis = new BufferedInputStream(new FileInputStream(file));
				    byte[] buffer = new byte[fis.available()];
				    fis.read(buffer);
				    fis.close();
				    response.reset();
				    //乱码处理
				    //先去掉文件名称中的空格,然后转换编码格式为utf-8,保证不出现乱码,这个文件名称用于浏览器的下载框中自动显示的文件名
				    response.addHeader("Content-Disposition", "attachment;filename=" + new String(file.getName().replaceAll(" ", "").getBytes("utf-8"),"iso8859-1"));
				    response.addHeader("Content-Length", "" + file.length());
				    OutputStream os = new BufferedOutputStream(response.getOutputStream());
				    response.setContentType("application/octet-stream");
				    os.write(buffer);//输出文件
				    os.flush();
				    os.close();//关闭流，释放资源！
			} catch (Exception e) {
				e.printStackTrace();
			}
			file.delete();
		}
	}
}
